<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          left-icon="phone"
          name="userAccount"
          label="手机号"
          placeholder="请填写手机号"
      />
      <van-field
          v-model="userCode"
          center
          type="digit"
          left-icon="setting"
          name="userPassword"
          label="验证码"
          placeholder="请填写验证码"
      >
        <template #button>
          <van-button v-if="!countdown" @click="sendCode" size="small" type="primary">发送验证码</van-button>
          <van-button v-else size="small">{{ remainingTime }}s</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div style="
    color: #1677ff;
    font-size: 16px;
    margin-right: 32px;
    display: flex;
    justify-content: flex-end;
    ">
      <span @click="toRegister">注册</span>
    </div>


    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>


<script setup lang="ts">
import { ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {showToast} from "vant";
import {sendPhone} from "../../api/phoneApi.ts";
import { loginPhone} from "../../api/userApi.ts";
import {userStore} from "../../stores/user/user.ts";
import {initConnection} from '../../ws/socketWork.ts';


const userAccount = ref('');
const userCode = ref('');
const router = useRouter();
const route = useRoute();
const countdown = ref(false);
const remainingTime = ref(60);
const userStoreAPI = userStore();//当前用户存储

console.log("redirect",route.query?.redirect);


const onSubmit = () => {
  //校验参数
  if (userAccount.value.length != 11){
    showToast("手机号不正确");
    return;
  }

  if (userCode.value == ''){
    showToast("请填写验证码");
    return;
  }

  const data = {
    phone: userAccount.value,
    code: userCode.value
  };

  loginPhone(data).then(res => {
    // 兼容新格式 code: 0 和旧格式 code: 200
    if (res.code === 0 || res.code === 200){
      // 新格式：res.data.user，旧格式：res.data
      const userData = res.data?.user || res.data;
      //缓存用户信息
      userStoreAPI.setCurrentUser(userData);

      //判断是否是新注册的用户(是否选择了标签)
      if (userData.userStatus == 1){
        //跳转到选择标签页面
        router.push('/genderSelect');

      }else{
        //直接重定向
        const redirectUrl = route.query?.redirect ?? '/index';//如果没有就默认时index首页
        if (redirectUrl === '/index') {
          router.replace('/index');
        } else {//redirectUrl == 'http://localhost:5173/user'
          if (typeof redirectUrl === "string") {
            window.location.href = redirectUrl + "";
          }
        }
      }

      //进行创建连接ws
      // initConnection();
      self.postMessage(`{"type":"initWS","value":${userData.id}}`);
    }else {
      showToast(res.data?.message);
    }
  });
};


//跳转到注册页面
const toRegister = ()=>{
  router.push('/register');
}



//发送验证码方法
const sendCode = ()=>{
  //不能一直发送
  if (remainingTime.value!=60){
    return;
  }


  //校验
  if (userAccount.value == ''){
    showToast("请填写手机号");
    return;
  }
  if (userAccount.value.length !== 11){//手机号11位
    showToast("手机号不正确");
    return;
  }

  //用发送手机号验证码
  sendPhone(userAccount.value).then(res =>{
    console.log("res",res);
    if (200 == res.code){//成功
      showToast("验证码已发送");
      countdown.value = true;
      const timer = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--;
        } else {
          clearInterval(timer);
          countdown.value = false;
          remainingTime.value = 60;
        }
      }, 1000);
    }else {//失败
      showToast(res.data?.message);
    }
  }).catch(err => {
    showToast("错误");
  });
};


</script>



<style scoped>

</style>